<template>
  <div class="uploader" :class="className">
    <slot name="text">
      <van-button
        type="primary"
        :loading="loading"
        v-if="!finished"
        @click="onUpload"
      >{{uploaderText}}</van-button>
    </slot>
    <slot name="image">
      <van-image width="100%" height="200" :src="url" fit="contain" />
    </slot>
    <van-cell-group>
      <van-field v-model="filePath" placeholder="文件路径" />
    </van-cell-group>
    <slot name="ext">
      <pre>{{res}}</pre>
    </slot>
    <slot name="reset">
      <van-button type="danger" :loading="loading" v-if="finished" @click="onReset">
        <van-icon name="cross" />
        <span>重新上传</span>
      </van-button>
    </slot>
  </div>
</template>
<script>
import { Icon, Cell, Button, Image, Field } from 'vant'
export default {
  components: {
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [Field.name]: Field,
    [Image.name]: Image
  },
  name: 'uploader',
  props: {
    scope: String,
    type: String,
    ratio: Number
  },
  data () {
    return {
      uploaderText: '上传',
      filePath: '',
      res: '',
      url: '',
      loading: false,
      finished: false
    }
  },
  computed: {
    className () {
      return this.class
    },
    isLoading () {
      return !!this.loading
    },
    useScope () {
      return this.scope ? this.scope : 'default'
    },
    allowType () {
      if (this.type) {
        return this.type
      }
      return 'image'
    },
    params () {
      return {
        scope: this.useScope,
        type: this.allowType,
        ratio: this.ratio
      }
    }
  },
  methods: {
    onUpload () {
      new Promise((resolve, reject) => {
        this.jsBridge.uploadAttach(this.params, res => {
          return resolve(res)
        })
      }).then(res => {
        this.loading = true
        this.uploaderText = '正在上传...'
        this.listenUploadComplete()
      })
      this.listenUploadComplete()
    },
    onReset () {
      this.finished = false
      this.uploaderText = '上传'
      this.filePath = ''
    },
    listenUploadComplete () {
      this.jsBridge.uploadComplete(res => {
        console.log('回调监听: ', res)
        console.log(res)
        this.res = res
        this.loading = false
        if (res && res.path) {
          this.finished = true
          this.uploaderText = '上传完成'
          this.filePath = res.path
          this.url = res.url
        } else {
          console.log(res)
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.uploader {
}
</style>
